//
//  LeaClothingBasicImageView.m
//  LeaClothing
//
//  Created by LeaClothing on 18/5/20.
//  Copyright (c) 2018年 LeaClothing. All rights reserved.
//

#import "LeaClothingBasicImageView.h"

#import <MobileCoreServices/MobileCoreServices.h>
#import <AssetsLibrary/AssetsLibrary.h>

#define ORIGINAL_MAX_WIDTH 640.0f
@import Photos;
@interface LeaClothingBasicImageView ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (strong , nonatomic) UIImagePickerController* imagePickerVC;
@property (strong , nonatomic) UITapGestureRecognizer *assSingleTap;
@end
@implementation LeaClothingBasicImageView

-(void)awakeFromNib{
    [super awakeFromNib];
    [self canReceiveAction:YES];
    [self dfMakeToCircle:YES];
}

-(instancetype)init{
    if (self=[super init]) {
        [self canReceiveAction:YES];
        [self dfMakeToCircle:YES];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
}

- (UIViewController *)theDFViewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

- (void)dfEditPortrait {
    
    UIAlertController *alertController;
    __block NSUInteger blockSourceType = 0;
    alertController = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        blockSourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.imagePickerVC = [[UIImagePickerController alloc] init];
        self.imagePickerVC.delegate = self;
        self.imagePickerVC.allowsEditing = YES;
        self.imagePickerVC.sourceType = blockSourceType;
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusNotDetermined) {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if(status == PHAuthorizationStatusAuthorized) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                    });
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [[self theDFViewController] dismissViewControllerAnimated:YES completion:nil];
                    });
                }
            }];
            
            [[self theDFViewController]  presentViewController:self.imagePickerVC animated:YES completion:^{
                
            }];
        }else if(status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted){
            // 无权限
            NSString *msg = @"请允许应用程序在iPhone的“设置-隐私-照片”选项中访问您的照片";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:cancelAction];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[self theDFViewController]  presentViewController:alertController animated:YES completion:nil];
            });
        }else{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[self theDFViewController] presentViewController:self.imagePickerVC animated:YES completion:nil];
            });
        }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            //相机
            blockSourceType = UIImagePickerControllerSourceTypeCamera;
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = blockSourceType;
            //相机权限
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
                authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
            {
                // 无权限
                NSString *msg = @"请允许应用程序在iPhone的“设置-隐私-相机”选项中访问您的相机";
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[self theDFViewController] presentViewController:alertController animated:YES completion:nil];
                });
                
            }else if(authStatus == AVAuthorizationStatusNotDetermined){
                ([AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted == YES) {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [[self theDFViewController] presentViewController:imagePickerController animated:YES completion:^{
                            }];
                        });
                    }else{
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [[self theDFViewController] dismissViewControllerAnimated:YES completion:nil];
                        });
                    }
                }]);
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[self theDFViewController] presentViewController:imagePickerController animated:YES completion:nil];
            });
        }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        return;
    }]];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[self theDFViewController] presentViewController:alertController animated:YES completion:nil];
    });
}

- (void)showAnUnauthorizedPromptAlertView:(NSString*)msg{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tip" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"Sure" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:sureAction];
    [[self theDFViewController] presentViewController:alert animated:YES completion:nil];
}

- (void)getThePhotoLibarayPhotosImg{
    // PhotoLibrary
    if ([self isPhotoLibraryAvailable]) {
        self.imagePickerVC = [[UIImagePickerController alloc] init];
        self.imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        self.imagePickerVC.mediaTypes = mediaTypes;
        self.imagePickerVC.delegate = self;
        [[self theDFViewController] presentViewController:self.imagePickerVC
                                                 animated:YES
                                               completion:^(void){
                                                   NSLog(@"Picker View Controller is presented");
                                               }];
    }
}


#pragma mark -- setting and getter
-(void)dfMakeToCircle:(BOOL)circle{
    self.layer.masksToBounds = circle;
    if (circle) {
        self.layer.cornerRadius = self.bounds.size.width/2;
    }
    
}
-(BOOL)dfMakeToCircle{
    return self.layer.masksToBounds;
}

-(void)canReceiveAction:(BOOL)receiveAction{
    if (receiveAction) {
        self.userInteractionEnabled = YES;
        self.assSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dfEditPortrait)];
        [self addGestureRecognizer:self.assSingleTap];
    }
    if (!receiveAction) {
        self.userInteractionEnabled = NO;
        [self.assSingleTap removeTarget:self action:@selector(dfEditPortrait)];
        self.assSingleTap=nil;
    }
}
-(BOOL)isCanReceiveAction{
    return self.userInteractionEnabled;
}

//#pragma mark VPImageCropperDelegate
//- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
//    self.image = editedImage;
//    [cropperViewController dismissViewControllerAnimated:YES completion:^{
//
//        if (self.delegate&&[self.delegate respondsToSelector:@selector(leaClothingBasicImageView: didSelectImage:)]) {
//            [self.delegate leaClothingBasicImageView:self didSelectImage:editedImage];
//        }
//    }];
//}
//
//- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
//    [cropperViewController dismissViewControllerAnimated:YES completion:^{
//
//    }];
//}

#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
 
    [self.imagePickerVC dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (self.delegate&&[self.delegate respondsToSelector:@selector(leaClothingBasicImageView: didSelectImage:)]) {
            [self.delegate leaClothingBasicImageView:self didSelectImage:portraitImg];
        }
//        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, [self theDFViewController].view.frame.size.width, [self theDFViewController].view.frame.size.width) limitScaleRatio:3.0];
//        imgEditorVC.delegate = self;
        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [[self theDFViewController] presentViewController:imgEditorVC animated:YES completion:^{
//
//            }];
//        });
    }];

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.imagePickerVC dismissViewControllerAnimated:YES completion:^{}];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    
    NSLog(@"saved..");
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

@end
